package com.test.qpbgboot.base.quartz;

import com.test.qpbgboot.base.utils.SpringContextUtils;
import com.test.qpbgboot.schedule.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.util.Date;

/**
 * 预约开始时间前五分钟，自动把订单状态改为已参加，谢绝退款
 */
@Slf4j
public class AutoAttendedJob implements Job {

    private static final String orderNoString = "orderNo";

    public static void setJob(String orderNo, Date triggerTime)
            throws SchedulerException {
        log.debug("生成-自动确认参加-定时任务，参数:orderNo={},triggerTime={}",
                orderNo, triggerTime);

        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Scheduler scheduler = schedulerFactory.getScheduler();

        JobDetail jobDetail = JobBuilder.newJob(AutoAttendedJob.class)
                .withIdentity("autoAttendedJobDetail-" + orderNo,
                        "AUTO_ATTENDED_JOB")
                .usingJobData(orderNoString, orderNo)
                .storeDurably()
                .build();
        Trigger trigger = TriggerBuilder.newTrigger()
                .startAt(triggerTime)
                .build();

        scheduler.scheduleJob(jobDetail, trigger);
        scheduler.start();
    }


    @Override
    public void execute(JobExecutionContext jobExecutionContext)
            throws JobExecutionException {
        log.debug("自动确认参加-定时任务");//预定时间开始前5分钟

        String orderNo = jobExecutionContext.getJobDetail()
                .getJobDataMap().getString(orderNoString);

        OrderService orderService =
                SpringContextUtils.getBean(OrderService.class);
        orderService.autoAttendedJobImpl(orderNo);
    }
}
